<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="set">创建</button>
    <button class="get">获取</button>
</body>
<script>
    var set = document.getElementsByClassName("set")[0];
    var get = document.getElementsByClassName("get")[0];

    // 如何获取cookie?
    // cookie 的存取都依赖于 document.cookie   (类型  字符串类型)
    //  cookie 存储的时候是一条一条的的存的,取的时候 一次性获取所有数据 用"; "分隔

    set.onclick = function () {
        // var date = new Date();
        // date.setDate(date.getDate() + 7);

        // document.cookie = "user=a123123; expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "pwd=123123; expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "phone=17386141517; expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "email=123123@qq.com; expires=" + date.toUTCString() + ";path=/";


        setCookie("user", "a123123", 31);
        setCookie("pwd", "123123", 31);
        setCookie("phone", "17386141517", 31);
        setCookie("email", "123123@qq.com", 31);
    }

    get.onclick = function () {
        console.log(getCookie("user"));
        console.log(getCookie("pwd"));
        console.log(getCookie("phone"));
        console.log(getCookie("email"));
        console.log(getCookie("heihei"));
    }

    // 对应键名设置cookie
    function setCookie(key, value, day, path = "/") {
        var date = new Date();
        date.setDate(date.getDate() + day);

        if (day != undefined) { // 有参数 => 设置过期时间  => 指定时间后过期
            document.cookie = key + "=" + value + "; expires=" + date.toUTCString() + ";path=" + path;
        } else { //没有参数 => 不设置过期时间 => 浏览器关闭过期
            document.cookie = key + "=" + value + ";path=" + path;
        }
    }

    // 对应键名获取cookie
    function getCookie(key) { // 传入的键名
        var cookie = document.cookie;
        if (cookie) {
            var list = cookie.split("; ");
            // console.log(list);
            for (var i = 0; i < list.length; i++) {
                var item = list[i];  // 'user=a123123', 'pwd=123123'
                var name = item.split("=")[0]; //解析的键名
                var val = item.split("=")[1];
                if (key === name) {
                    return val;
                }
            }

        }
        return ""; // 找不到 默认返回 ""
    }
</script>

</html>